<?php
include "mysql_connect.php";
include "common.php";
include "mapapi.php";
require_once 'vendor/autoload.php';
include "phpmail/mail.php";

$method=$_REQUEST['method'];
if($method=="login")
{
    dologin();
    mysqli_close($_SESSION['mysqli_link']);
    exit;
}

if(!(isset($_COOKIE['username']) && $_COOKIE['userid']&& $_COOKIE['userrole']))
{
    header('Location: index.html');
    exit;
}

switch ($method)
{
	case 'exportevalcsv':
		exportevalcsv();
		break;
	case "checkpwd":
		checkpwd();
		break;
	case "companylogoupload":
		companylogoupload();
		break;
    case "getMerchantTableByUserid":
        getMerchantTableByUserid();
        break;
    case "getBriefingTable":
        getBriefingTable();
        break;
    case "getMerchantSelectByUserid":
        getMerchantSelectByUserid();
        break;
    case "getIndustryOption":
        getIndustryOption();
        break;
    case "getIndustryOptionDetail":
        getIndustryOptionDetail();
        break;
    case "getStoreTableByMerchantUUID":
        getStoreTableByMerchantUUID();
        break;
    case "getMerchantInfoByMerchantUUID":
        getMerchantInfoByMerchantUUID();
        break;
    case "getFloorsByMerchantUUID":
        getFloorsByMerchantUUID();
        break;
    case "getFloors":
        getFloors();
        break;
    case "getMerchantFloorInfo":
        getFloorsByMerchantUUID();
        break;
    case "getMerchanttype":
        getMerchanttype();
        break;
    case "addStore":
        addStore();
        break;
    case "modifyStore":
        modifyStore();
        break;
    case "delStore":
        delStore();
        break;
    case "delMerchant":
        delMerchant();
        break;
    case "addMerchant":
        addMerchant();
        break;
    case "modifyMerchant":
        modifyMerchant();
        break;
    case "getServers":
        getServers();
        break;
    case "getRoles":
        getRoles();
        break;
    case "getMerchantInRoles":
        getMerchantInRoles();
        break;
    case "getLocation":
        getLocation();
        break;
    case "getRolesTable":
        getRolesTable();
        break;
    case "getMerchantsSelect":
        getMerchantsSelect();
        break;
    case "addRole":
        addRole();
        break;
    case "modifyRole":
        modifyRole();
        break;
    case "getRolesMerchant":
        getRolesMerchant();
        break;
    case "delRole":
        delRole();
        break;
    case "getUsersTable":
        getUsersTable();
        break;
    case "addUser":
        addUser();
        break;
    case "modifyUser":
        modifyUser();
        break;
    case "delUser":
        delUser();
        break;
    case "checkWidgetEcho":
        checkWidgetEcho();
        break;
    case "changepwd":
        changepwd();
        break;
    case "resetUPwd":
        resetUPwd();
        break;
    case "getServersTable":
        getServersTable();
        break;
    case "addServer":
        addServer();
        break;
    case "modifyServer":
        modifyServer();
        break;
    case "delServer":
        delServer();
        break;
    case "getIndusTable":
        getIndusTable();
        break;
    case "addChildIndustry":
        addChildIndustry();
        break;
    case "logout":
        logout();
        break;

}
mysqli_close($_SESSION['mysqli_link']);

function transdate($strDMY)
{
	$arrDMY=explode("/",$strDMY);
	if(count($arrDMY)==3)
	{
		return $arrDMY[2]."年".$arrDMY[1]."月".$arrDMY[0]."日";
	}
	else{return $strDMY;}
}

function get_basename($filename){
    return preg_replace('/^.+[\\/]/', '', $filename);
}

function convertToPDF($docxfile)
{
	$pi=pathinfo($docxfile);
	$dname=$pi['dirname'];
	$abpath=dirname(__FILE__);
	exec("libreoffice --headless --convert-to pdf:writer_pdf_Export \"".$abpath."/".$docxfile."\" --outdir ".$abpath."/".$dname);
	file_put_contents("upload/debug.txt","libreoffice --headless --convert-to pdf:writer_pdf_Export ".$abpath."/".$docxfile." --outdir ".$abpath."/".$dname);
	return str_replace(".docx",".pdf",$docxfile);
}



function exportevalcsv()
{
	$title_arr=array();
	$data=array();
	$sql_cols="select COLUMN_NAME,COLUMN_COMMENT from information_schema.`COLUMNS` where TABLE_SCHEMA='briefing_db' and  TABLE_NAME='evalresult';"	;
	$res_cols=mysqli_query($_SESSION['mysqli_link'], $sql_cols);
	while($arrres=mysqli_fetch_assoc($res_cols))
	{
		$oc=$arrres['COLUMN_COMMENT'];
		array_push($title_arr,$oc);
	}
	
	$sql="select * from evalresult;";
	$res=mysqli_query($_SESSION['mysqli_link'], $sql);
	while($arrres=mysqli_fetch_assoc($res))
	{
		array_push($data,$arrres);
	}
	
	$filename="evalresult_".date("Y-m-d H:i:s",time());
	export_csv($data,$title_arr,$filename);

}

function export_csv($data,$title_arr,$file_name=''){
    ini_set("max_execution_time", "3600");

    $csv_data = '';

    /** 标题 */
    $nums = count($title_arr);

    for ($i = 0; $i < $nums - 1; ++$i) {
        //$csv_data .= '"' . $title_arr[$i] . '",';
        $csv_data .= $title_arr[$i] . ',';
    }
    if ($nums > 0) {
        $csv_data .= $title_arr[$nums - 1] . "\r\n";
    }

    foreach ($data as $k => $row) {
        $_tmp_csv_data = '';
        foreach ($row as $key => $r){
            $row[$key] = str_replace("\"", "\"\"", $r);
            $row[$key] = str_replace(",", "，", $r);

            if ( $_tmp_csv_data == '' ) {
                $_tmp_csv_data = $row[$key];
            }
            else {
                $_tmp_csv_data .= ','. $row[$key];
            }

        }

        $csv_data .= $_tmp_csv_data.$row[$nums - 1] . "\r\n";
        unset($data[$k]);
    }

    $csv_data = mb_convert_encoding($csv_data, "cp936", "UTF-8");
    $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
    // 解决IE浏览器输出中文名乱码的bug
    if(preg_match( '/MSIE/i', $_SERVER['HTTP_USER_AGENT'] )){
        $file_name = urlencode($file_name);
        $file_name = iconv('UTF-8', 'GBK//IGNORE', $file_name);
    }
    $file_name = $file_name . '.csv';
    header('Content-Type: application/download');
    header("Content-type:text/csv;");
    header("Content-Disposition:attachment;filename=" . $file_name);
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    echo $csv_data;
    exit();
}

function companylogoupload()
{
	if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));
    }
	//print_r($_FILES);
	//die(makeresultjson(110,"xxx"));
	/*Array
(
    [file_data] => Array
        (
            [name] => stopshop.png
            [type] => image/png
            [tmp_name] => /tmp/phpL5hl0d
            [error] => 0
            [size] => 43995
        )

)
	 * */

	
	if ((($_FILES["file_data"]["type"] == "image/gif")
	|| ($_FILES["file_data"]["type"] == "image/jpeg")
	|| ($_FILES["file_data"]["type"] == "image/pjpeg")
	|| ($_FILES["file_data"]["type"] == "image/png"))
	&& ($_FILES["file_data"]["size"] < 2000000))
	  {
	  if ($_FILES["file_data"]["error"] > 0)
	    {
	    //echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
	    die(makeresultjson("-98",$_FILES["file"]["error"]));
	    }
	  else
	    {
	    //echo "Upload: " . $_FILES["file"]["name"] . "<br />";
	    //echo "Type: " . $_FILES["file"]["type"] . "<br />";
	    //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
	    //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
	
//	    if (file_exists("upload/" . $_FILES["file_data"]["name"]))
//	      {
//	      die(makeresultjson(97," already exists. "));
//	      }
//	    else
		  $exname=substr(strrchr($_FILES["file_data"]["type"], '/'), 1);
		  if($_REQUEST['username']!="")
	      {
	      move_uploaded_file($_FILES["file_data"]["tmp_name"],
	      "upload/" . $_REQUEST['username'].".".$exname);
	      //echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
	      
	      
	      $sql_username="select id from user where username='".$_REQUEST['username']."'";
		    $rs=mysqli_query($_SESSION['mysqli_link'],$sql_username);
		    $arrrs=mysqli_fetch_assoc($rs);
		    if(!empty($arrrs))
		    {
		    	$sql_logopath="update user set logopath='"."upload/" . $_REQUEST['username'].".".$exname."' where username='".$_REQUEST['username']."'";
		    }
		    else //first time
		    {
		    	$sql_logopath="insert into user (username,logopath,role_id) values('".$_REQUEST['username']."','"."upload/" . $_REQUEST['username'].".".$exname."','".$_REQUEST['role_id']."')";
		    }
	      
	      
        	mysqli_query($_SESSION['mysqli_link'], $sql_logopath);
	      
	      die(makeresultjson(0,"save ok"));
	      }
		  else
		  {
		  	die(makeresultjson(95,"need username"));
		  }
	    }
	  }
	else
	  {
	  die(makeresultjson(96,"Invalid file".json_encode($_FILES)));
	  }
}

function addChildIndustry()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();

    //name check;
    $sql_name="select id from industry where name='".$_REQUEST['childname']."' and level=2";
    $rs=mysqli_query($_SESSION['mysqli_link'],$sql_name);
    $arrrs=mysqli_fetch_assoc($rs);
    if(!empty($arrrs))
    {
        echo(makeresultjson("-3","childname echo."));
        return;
    }
    mysqli_autocommit($_SESSION['mysqli_link'],0);
    $sql="insert into industry (name,pid,level) values('".$_REQUEST['childname']."','".$_REQUEST['pid']."','2')";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    $newchild_id=mysqli_insert_id($_SESSION['mysqli_link']);
    writeLog($sql);
    if($result)
    {
        $newpath=",".$_REQUEST['pid'].",".$newchild_id.",";
        $sql_path="update industry set path='".$newpath."' where id='".$newchild_id."'";
        mysqli_query($_SESSION['mysqli_link'], $sql_path);
        mysqli_commit($_SESSION['mysqli_link']);
        echo(makeresultjson("0","ok"));


    }
    else
    {
        mysqli_rollback($_SESSION['mysqli_link']);
        echo(makeresultjson("-1","sql_error@createServer"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function getIndusTable()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();

    $arr_res=array();


    $sql="select i1.id as i1id,i1.name as i1name,i2.name as i2name from industry i1 left join industry i2 on i1.id=i2.pid where i1.pid=0;";


    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    $arrid_distinct=array();
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        if(!in_array($row['i1id'],$arrid_distinct))
        {
            $arr_res_oneline = array();
            $arr_res_oneline['id']=$row['i1id'];
            $arr_res_oneline['name']=$row['i1name'];
            $arr_res_oneline['childnames']=$row['i2name'];
            array_push($arr_res,$arr_res_oneline);
            array_push($arrid_distinct,$row['i1id']);
        }
        else
        {
            foreach ($arr_res as $k=>$oa)
            {
                if($oa['id']==$row['i1id'])
                {
                    $arr_res[$k]['childnames'].=",".$row['i2name'];
                    break;
                }
            }
        }



    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function dieIfNotRole1()
{
    if($_COOKIE['userrole']!="1")
    {
        die(makeresultjson("-99","need logina"));

    }
}
function resetUPwd()
{

    dieIfNotRole1();
    $sql_reset_pwd="update user set pwd='".md5($_REQUEST['np'])."' where id='".$_REQUEST['id']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql_reset_pwd);

    if($result)
    {
        mysqli_commit($_SESSION['mysqli_link']);
        echo(makeresultjson("0","ok"));
    }
    else
    {
        mysqli_rollback($_SESSION['mysqli_link']);
        echo(makeresultjson("-1","sqlerror:$sql_reset_pwd"));
    }
}

function delServer()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();

    //mall is exist?
    $sql_merchant="select * from merchant where server_id='".$_REQUEST['id']."'";
    $result_merchant = mysqli_query($_SESSION['mysqli_link'], $sql_merchant);

    $arrmerchant=mysqli_fetch_assoc($result_merchant);
    if(!empty($arrmerchant))
    {
        echo(makeresultjson("-2","not allow delete server where have merchant"));
    }
    else
    {
        mysqli_autocommit($_SESSION['mysqli_link'],0);
        $sql="delete from  server  where id='".$_REQUEST['id']."'";
        $result1 = mysqli_query($_SESSION['mysqli_link'], $sql);
        writeLog($sql);


        if($result1)
        {
            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0","ok"));
        }
        else
        {
            mysqli_rollback($_SESSION['mysqli_link']);
            echo(makeresultjson("-1","sqlerror:$result1"));
        }

        writeLog($sql);
    }
    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function modifyServer()
{
    if (!isset($_COOKIE['userid']) || !$_COOKIE['userrole']) {
        die(makeresultjson("-99", "need login"));

    }

    dieIfNotRole1();

    mysqli_autocommit($_SESSION['mysqli_link'], 0);

    $server_id = $_REQUEST['id'];
    $sql = "update server set name='" . $_REQUEST['name'] . "',description='" . $_REQUEST['desc'] . "'  where id='" . $server_id . "'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);;
    writeLog($sql);
    if ($result) {


        mysqli_commit($_SESSION['mysqli_link']);
        echo(makeresultjson("0", "ok"));

    }
    else
    {
        echo(makeresultjson("-1","sql_error@ModifyServer"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function addServer()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();

    //name check;
    $sql_name="select id from server where name='".$_REQUEST['name']."'";
    $rs=mysqli_query($_SESSION['mysqli_link'],$sql_name);
    $arrrs=mysqli_fetch_assoc($rs);
    if(!empty($arrrs))
    {
        echo(makeresultjson("-3","name echo."));
        return;
    }
    mysqli_autocommit($_SESSION['mysqli_link'],0);
    $sql="insert into server (name,description) values('".$_REQUEST['name']."','".$_REQUEST['desc']."')";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    mysqli_insert_id($_SESSION['mysqli_link']);
    writeLog($sql);
    if($result)
    {


        mysqli_commit($_SESSION['mysqli_link']);
        echo(makeresultjson("0","ok"));


    }
    else
    {
        mysqli_rollback($_SESSION['mysqli_link']);
        echo(makeresultjson("-1","sql_error@createServer"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function getServersTable()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();


    $sql="select * from server;";


    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        $arr_res_oneline['desc']=$row['description'];

        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function changepwd()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $oldpwd=$_POST['oldpwd'];
    $newpwd=$_POST['newpwd1'];
    $sql_check="select * from user where pwd='".md5($oldpwd)."' and id='".$_REQUEST['userid']."'";
    writeLog($sql_check);
    $result = mysqli_query($_SESSION['mysqli_link'], $sql_check);
    $arrrs=mysqli_fetch_assoc($result);
    if(empty($arrrs))
    {
        echo(makeresultjson("-4","old error"));
    }
    else
    {
        $sql="update user set pwd='".md5($newpwd)."' where id='".$_REQUEST['userid']."'";
        $result = mysqli_query($_SESSION['mysqli_link'], $sql);
        if($result)
        {
            echo(makeresultjson("0","ok"));
        }
        else
        {
            echo(makeresultjson("-1","sqlerror:changepwd"));
        }
    }

    return;
}

function checkpwd()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $oldpwd=$_POST['oldpwd'];
    
    $sql_check="select * from user where pwd='".md5($oldpwd)."' and id='".$_REQUEST['userid']."'";
    writeLog($sql_check);
    $result = mysqli_query($_SESSION['mysqli_link'], $sql_check);
    $arrrs=mysqli_fetch_assoc($result);
    if(empty($arrrs))
    {
        echo(makeresultjson("-4","old error"));
    }
    else
    {
        
        {
            echo(makeresultjson("0","ok"));
        }
        
    }

    return;
}

function checkWidgetEcho()
{
    $tbname=$_REQUEST['tbname'];
    $clmname=$_REQUEST['clmname'];
    $vl=$_REQUEST['vl'];
    $noteqid=$_REQUEST['noteqid'];
    $sql="select 1 from ".$tbname." where ".$clmname."='".$vl."' and id <>'".$noteqid."'";
    writeLog($sql);
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    $arrrs=mysqli_fetch_assoc($result);
    if(empty($arrrs))
    {
        //not echo
        echo(makeresultjson("0","ok"));
    }
    else
    {
        echo(makeresultjson("-3","clmname echo"));
    }
    return;
}

function delUser()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    dieIfNotRole1();

    {
    		$sql="select logopath from user where id='".$_REQUEST['id']."'";
    		$result_logopath = mysqli_query($_SESSION['mysqli_link'], $sql);
    		$arrlogo=mysqli_fetch_assoc($result_logopath);
    		$logopath=$arrlogo['logopath'];
    		$abpath=dirname(__FILE__);
    		$unlink_res=unlink($abpath."/".$logopath);
    	
        mysqli_autocommit($_SESSION['mysqli_link'],0);
        $sql="delete from  user  where id='".$_REQUEST['id']."'";
        $result1 = mysqli_query($_SESSION['mysqli_link'], $sql);
        writeLog($sql);


        if($result1)
        {
            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0","ok".$unlink_res));
        }
        else
        {
            mysqli_rollback($_SESSION['mysqli_link']);
            echo(makeresultjson("-1","sqlerror:$result1"));
        }

        writeLog($sql);
    }
    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function modifyUser()
{
    if (!isset($_COOKIE['userid']) || !$_COOKIE['userrole']) {
        die(makeresultjson("-99", "need login"));

    }
    dieIfNotRole1();

    mysqli_autocommit($_SESSION['mysqli_link'], 0);

    $user_id = $_REQUEST['id'];
    $sql = "update user set username='" . $_REQUEST['name'] . "',email='" . $_REQUEST['email']. "',email2='" . $_REQUEST['email2'] . "',emailname='" . $_REQUEST['emailname'] . "',email2name='" . $_REQUEST['email2name'] . "',companyname='" . $_REQUEST['companyname'] . "',tel='" . $_REQUEST['tel'] . "',address='" . $_REQUEST['address'] . "',price188a='" . $_REQUEST['price188a'] . "',price188b='" . $_REQUEST['price188b'] . "',price188c='" . $_REQUEST['price188c'] . "',price132='" . $_REQUEST['price132'] . "',role_id='".$_REQUEST['role_id']."' where id='" . $user_id . "'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);;
    writeLog($sql);
    if ($result) {


            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0", "ok"));

    }
    else
    {
        echo(makeresultjson("-1","sql_error@ModifyUser"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function addUser()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();
    //name check;
    $sql_username="select id from user where username='".$_REQUEST['name']."' or email='".$_REQUEST['email']."'";
    $rs=mysqli_query($_SESSION['mysqli_link'],$sql_username);
    $arrrs=mysqli_fetch_assoc($rs);
    if(!empty($arrrs))
    {
        //echo(makeresultjson("-3","username echo."));
        //return;
        //$user_id = $_REQUEST['id'];
    		$sql = "update user set username='" . $_REQUEST['name'] . "',email='" . $_REQUEST['email']. "',email2='" . $_REQUEST['email2'] . "',emailname='" . $_REQUEST['emailname'] . "',email2name='" . $_REQUEST['email2name'] . "',companyname='" . $_REQUEST['companyname'] . "',tel='" . $_REQUEST['tel'] . "',address='" . $_REQUEST['address'] . "',price188a='" . $_REQUEST['price188a'] . "',price188b='" . $_REQUEST['price188b'] . "',price188c='" . $_REQUEST['price188c'] . "',price132='" . $_REQUEST['price132'] . "',role_id='".$_REQUEST['role_id']."' where username='".$_REQUEST['name']."'";

    }
    else
    {
    		$sql="insert into user (username,email,email2,emailname,email2name,companyname,tel,address,price188a,price188b,price188c,price132,role_id) values('".$_REQUEST['name']."','".$_REQUEST['email']."','".$_REQUEST['email2']."','".$_REQUEST['emailname']."','".$_REQUEST['email2name']."','".$_REQUEST['companyname']."','".$_REQUEST['tel']."','".$_REQUEST['address']."','".$_REQUEST['price188a']."','".$_REQUEST['price188b']."','".$_REQUEST['price188c']."','".$_REQUEST['price132']."','".$_REQUEST['role_id']."')";
    }
    mysqli_autocommit($_SESSION['mysqli_link'],0);
    
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    mysqli_insert_id($_SESSION['mysqli_link']);
    writeLog($sql);
    if($result)
    {


        mysqli_commit($_SESSION['mysqli_link']);
        echo(makeresultjson("0","ok"));


    }
    else
    {
        mysqli_rollback($_SESSION['mysqli_link']);
        echo(makeresultjson("-1","sql_error@createUser"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function getUsersTable()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();


    $sql="select user.id,user.username,user.email,user.email2,user.emailname,user.email2name,user.companyname,user.tel,user.address,user.price188a,user.price188b,user.price188c,user.price132,user.logopath,role.name,role.id as rid from user inner join role on role.id=user.role_id;";


    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['username'];
        $arr_res_oneline['email']=$row['email'];
		$arr_res_oneline['emailname']=$row['emailname'];
		$arr_res_oneline['email2']=$row['email2'];
		$arr_res_oneline['email2name']=$row['email2name'];
		$arr_res_oneline['companyname']=$row['companyname'];
		$arr_res_oneline['tel']=$row['tel'];
		$arr_res_oneline['address']=$row['address'];
		$arr_res_oneline['price188a']=$row['price188a'];
		$arr_res_oneline['price188b']=$row['price188b'];
		$arr_res_oneline['price188c']=$row['price188c'];
		$arr_res_oneline['price132']=$row['price132'];
		$arr_res_oneline['logopath']=$row['logopath'];
        $arr_res_oneline['rolename']=$row['name'];
        $arr_res_oneline['roleid']=$row['rid'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}


function delRole()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();
    //store is exist?
    $sql_role_auth="select * from role_authority where role_id='".$_REQUEST['role_id']."'";
    $result_role_auth = mysqli_query($_SESSION['mysqli_link'], $sql_role_auth);

    $arrauth=mysqli_fetch_assoc($result_role_auth);
    if(!empty($arrauth))
    {
        echo(makeresultjson("-2","not allow delete role where have merchant"));
    }
    else
    {
        mysqli_autocommit($_SESSION['mysqli_link'],0);
        $sql="delete from  role  where id='".$_REQUEST['role_id']."'";
        $result1 = mysqli_query($_SESSION['mysqli_link'], $sql);
        writeLog($sql);


        if($result1)
        {
            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0","ok"));
        }
        else
        {
            mysqli_rollback($_SESSION['mysqli_link']);
            echo(makeresultjson("-1","sqlerror:$result1"));
        }

        writeLog($sql);
    }
    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function getRolesMerchant()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select merchant.id,merchant.name from role_authority ra inner join merchant on merchant.id=ra.merchant_id where role_id='".$_REQUEST['role_id']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function addRole()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();
    //merchantname check;
    $sql_rolename="select id from role where name='".$_REQUEST['name']."'";
    $rs=mysqli_query($_SESSION['mysqli_link'],$sql_rolename);
    $arrrs=mysqli_fetch_assoc($rs);
    if(!empty($arrrs))
    {
        echo(makeresultjson("-3","rolename echo."));
        return;
    }
    //$uuid=create_uuid();
    mysqli_autocommit($_SESSION['mysqli_link'],0);
    $sql="insert into role (name,description) values('".$_REQUEST['name']."','".$_REQUEST['description']."')";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    $role_id=mysqli_insert_id($_SESSION['mysqli_link']);
    writeLog($sql);
    if($result)
    {
        $arrMerchant=$_REQUEST['merchant'];
        if(!empty($arrMerchant))
        {
            foreach ($arrMerchant as $oneM) {
                $sql_role_auth="insert into role_authority (role_id,merchant_id) values ('".$role_id."','".$oneM."');";
                writeLog($sql_role_auth);
                $result=mysqli_query($_SESSION['mysqli_link'], $sql_role_auth);
            }
        }

        if($result)
        {

            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0","ok"));

        }
        else
        {
            mysqli_rollback($_SESSION['mysqli_link']);
            echo(makeresultjson("-1","sql_error@createrole_auth"));
        }
    }
    else
    {
        mysqli_rollback($_SESSION['mysqli_link']);
        echo(makeresultjson("-1","sql_error@createRole"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function modifyRole()
{
    if (!isset($_COOKIE['userid']) || !$_COOKIE['userrole']) {
        die(makeresultjson("-99", "need login"));

    }
    dieIfNotRole1();
    mysqli_autocommit($_SESSION['mysqli_link'], 0);

    $role_id = $_REQUEST['id'];
    $sql = "update role set name='" . $_REQUEST['name'] . "',description='" . $_REQUEST['description'] . "' where id='" . $role_id . "'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);;
    writeLog($sql);
    if ($result) {
        $sql_delete_role_auth = "delete from role_authority where role_id='" . $role_id . "'";
        mysqli_query($_SESSION['mysqli_link'], $sql_delete_role_auth);
        $arrMerchant = $_REQUEST['merchant'];
        if(!empty($arrMerchant))
        {
            foreach ($arrMerchant as $oneM) {
                $sql_role_auth = "insert into role_authority (role_id,merchant_id) values ('" . $role_id . "','" . $oneM . "');";
                writeLog($sql_role_auth);
                $result=mysqli_query($_SESSION['mysqli_link'], $sql_role_auth);
            }
        }

        if ($result) {

            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0", "ok"));

        } else {
            echo(makeresultjson("-1", "sql_error@createrole_auth"));
        }
    }
    else
    {
        echo(makeresultjson("-1","sql_error@ModifyRole"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function getMerchantsSelect()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    $sql="select * from merchant ;";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getRolesTable()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select * from role where id >1;";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        $arr_res_oneline['desc']=$row['description'];
        array_push($arr_res,$arr_res_oneline);
    }
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getLocation()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select * from ht_location where level='".$_REQUEST['level']."' and pid='".$_REQUEST['pid']."';";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getMerchanttype()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select * from merchanttype;";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}


function getServers()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select * from server;";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getRoles()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select * from role where id >1;";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getMerchantInRoles()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res=array();
    $sql="select role.id from role inner join role_authority ra on ra.role_id=role.id where merchant_id='".$_REQUEST['merchant_id']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}


function getFloorsByMerchantUUID()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    $sql="select floor.* from merchant_floor inner join floor on floor.id=merchant_floor.floor_id where merchant_uuid='".$_REQUEST['merchant_uuid']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getFloors()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    $sql="select * from floor";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function modifyStore()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $sql="update store set merchant_uuid='".$_REQUEST['merchant_uuid']."',name='".$_REQUEST['name']."',floor='".$_REQUEST['floor']."',area='".$_REQUEST['area']."',industry='".$_REQUEST['industry']."' where id='".$_REQUEST['store_id']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    writeLog($sql);
    if($result)
        echo(makeresultjson("0","ok"));
    else
        echo(makeresultjson("1","update fail"));
    return;
}

function delStore()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $sql="delete from  store  where id='".$_REQUEST['store_id']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    writeLog($sql);
    if($result)
        echo(makeresultjson("0","ok"));
    else
        echo(makeresultjson("1","delete fail"));
    return;
}

function delMerchant()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();
    //store is exist?

    $sql_store="select * from store where merchant_uuid='".$_REQUEST['merchant_uuid']."'";
    $result_store = mysqli_query($_SESSION['mysqli_link'], $sql_store);

    $arrstore1=mysqli_fetch_assoc($result_store);
    if(!empty($arrstore1))
    {
        echo(makeresultjson("-2","not allow delete merchant where have store"));
    }
    else
    {
        mysqli_autocommit($_SESSION['mysqli_link'],0);
        $sql="delete from  merchant  where uuid='".$_REQUEST['merchant_uuid']."'";
        $result1 = mysqli_query($_SESSION['mysqli_link'], $sql);
        writeLog($sql);

        $sql="delete from  merchant_floor  where merchant_uuid='".$_REQUEST['merchant_uuid']."'";
        $result2 = mysqli_query($_SESSION['mysqli_link'], $sql);
        writeLog($sql);

        $sql="delete from  role_authority  where merchant_id='".$_REQUEST['merchant_id']."'";
        $result3 = mysqli_query($_SESSION['mysqli_link'], $sql);
        writeLog($sql);

        if($result1&&$result2&$result3)
        {
            mysqli_commit($_SESSION['mysqli_link']);
            echo(makeresultjson("0","ok"));
        }
        else
        {
            mysqli_rollback($_SESSION['mysqli_link']);
            echo(makeresultjson("-1","sqlerror:$result1:$result2:$result3"));
        }

        writeLog($sql);
    }
    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function addStore()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $uuid=create_uuid();
    $sql="insert into store (uuid,merchant_uuid,name,floor,area,industry) values('".$uuid."','".$_REQUEST['merchant_uuid']."','".$_REQUEST['name']."','".$_REQUEST['floor']."','".$_REQUEST['area']."','".$_REQUEST['industry']."')";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    writeLog($sql);
    if($result)
        echo(makeresultjson("0","ok"));
    else
        echo(makeresultjson("1","insert fail"));
    return;
}

function addMerchant()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    dieIfNotRole1();
    //merchantname check;
    $sql_merchantname="select id from merchant where name='".$_REQUEST['name']."'";
    $rs=mysqli_query($_SESSION['mysqli_link'],$sql_merchantname);
    $arrrs=mysqli_fetch_assoc($rs);
    if(!empty($arrrs))
    {
        echo(makeresultjson("-3","merchantName echo."));
        return;
    }
    $uuid=create_uuid();
    mysqli_autocommit($_SESSION['mysqli_link'],0);
    $sql="insert into merchant (uuid,name,area,server_id,merchant_type,ht_location_info,address) values('".$uuid."','".$_REQUEST['name']."','".$_REQUEST['area']."','".$_REQUEST['server']."','".$_REQUEST['merchanttype']."','".$_REQUEST['location_info']."','".$_REQUEST['address']."')";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    $merchant_id=mysqli_insert_id($_SESSION['mysqli_link']);
    writeLog($sql);

    //E N location_info
    $sql_locationname="select name,pid from ht_location where path='".$_REQUEST['location_info']."'";
    $rsln=mysqli_query($_SESSION['mysqli_link'],$sql_locationname);
    $arrrsln=mysqli_fetch_assoc($rsln);


    if(!empty($arrrsln))
    {
        $locationname=$arrrsln['name'];
        $pid=$arrrsln['pid'];

        $sql_locationname_parent="select name from ht_location where id='".$pid."'";
        $rslnp=mysqli_query($_SESSION['mysqli_link'],$sql_locationname_parent);
        $arrrslnp=mysqli_fetch_assoc($rslnp);
        $locationname_p="";
        if(!empty($arrrslnp))
        {
            $locationname_p=$arrrslnp['name'];
        }

        $xandy=getXYInfo($locationname_p.$locationname);
        $arrxy=explode(",",$xandy);
        $sql_xy="update merchant set E='".$arrxy[0]."',N='".$arrxy[1]."' where id='".$merchant_id."'";
        mysqli_query($_SESSION['mysqli_link'], $sql_xy);
        writeLog($sql_xy);
    }

    if($result)
    {
        //$sql_floor="";
        $arrFloors=$_REQUEST['floor'];
        foreach ($arrFloors as $onef) {
            $sql_floor="insert into merchant_floor (merchant_uuid,floor_id) values ('".$uuid."','".$onef."');";
            writeLog($sql_floor);
            mysqli_query($_SESSION['mysqli_link'], $sql_floor);
        }
        if($result)
        {


            //$sql_role="";
            $arrroles=$_REQUEST['roles'];
            foreach ($arrroles as $orole) {
                $sql_role="insert into role_authority (merchant_id,role_id,`I`,`D`,`M`,`S`) values ('".$merchant_id."','".$orole."','1','0','0','1');";
                writeLog($sql_role);
                $result = mysqli_query($_SESSION['mysqli_link'], $sql_role);
               // $sql_role="select 22";
            }

            if($result)
            {
                mysqli_commit($_SESSION['mysqli_link']);
                echo(makeresultjson("0","ok"));
            }
            else
            {
                mysqli_rollback($_SESSION['mysqli_link']);
                echo(makeresultjson("-1","sql_error@createrole_auth:".$result));
            }

        }
        else
        {
            mysqli_rollback($_SESSION['mysqli_link']);
            echo(makeresultjson("-1","sql_error@createMerchantFloor"));
        }
    }
    else
    {
        mysqli_rollback($_SESSION['mysqli_link']);
        echo(makeresultjson("-1","sql_error@createMerchant"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function modifyMerchant()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    mysqli_autocommit($_SESSION['mysqli_link'],0);
    //$sql="insert into merchant (uuid,name,area,server_id,merchant_type,ht_location_info) values('".$uuid."','".$_REQUEST['name']."','".$_REQUEST['area']."','".$_REQUEST['server']."','".$_REQUEST['merchanttype']."','".$_REQUEST['location_info']."')";
    $merchant_id=$_REQUEST['mid'];
    $sql="update merchant set name='".$_REQUEST['name']."',area='".$_REQUEST['area']."',server_id='".$_REQUEST['server']."',merchant_type='".$_REQUEST['merchanttype']."',ht_location_info='".$_REQUEST['location_info']."',address='".$_REQUEST['address']."' where id='".$merchant_id."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    //$merchant_id=mysqli_insert_id($_SESSION['mysqli_link']);
    writeLog($sql);

    //E N location_info
    $sql_locationname="select name,pid from ht_location where path='".$_REQUEST['location_info']."'";
    $rsln=mysqli_query($_SESSION['mysqli_link'],$sql_locationname);
    $arrrsln=mysqli_fetch_assoc($rsln);


    if(!empty($arrrsln))
    {
        $locationname=$arrrsln['name'];
        $pid=$arrrsln['pid'];

        $sql_locationname_parent="select name from ht_location where id='".$pid."'";
        $rslnp=mysqli_query($_SESSION['mysqli_link'],$sql_locationname_parent);
        $arrrslnp=mysqli_fetch_assoc($rslnp);
        $locationname_p="";
        if(!empty($arrrslnp))
        {
            $locationname_p=$arrrslnp['name'];
        }

        $xandy=getXYInfo($locationname_p.$locationname);
        $arrxy=explode(",",$xandy);
        $sql_xy="update merchant set E='".$arrxy[0]."',N='".$arrxy[1]."' where id='".$merchant_id."'";
         mysqli_query($_SESSION['mysqli_link'], $sql_xy);
        writeLog($sql_xy);
    }

    if($result)
    {
        //$sql_floor="";
        $uuid=$_REQUEST['muuid'];
        $sql_delete_floors="delete from merchant_floor where merchant_uuid='".$uuid."'";
        mysqli_query($_SESSION['mysqli_link'], $sql_delete_floors);
        $arrFloors=$_REQUEST['floor'];
        foreach ($arrFloors as $onef) {
            $sql_floor="insert into merchant_floor (merchant_uuid,floor_id) values ('".$uuid."','".$onef."');";
            writeLog($sql_floor);
            mysqli_query($_SESSION['mysqli_link'], $sql_floor);
        }
        if($result)
        {


            //$sql_role="";
            $arrroles=$_REQUEST['roles'];
            $sql_delete_roles="delete from role_authority where merchant_id='".$merchant_id."'";
            mysqli_query($_SESSION['mysqli_link'], $sql_delete_roles);
            foreach ($arrroles as $orole) {
                $sql_role="insert into role_authority (merchant_id,role_id,`I`,`D`,`M`,`S`) values ('".$merchant_id."','".$orole."','1','0','1','1');";
                writeLog($sql_role);
                $result = mysqli_query($_SESSION['mysqli_link'], $sql_role);
                // $sql_role="select 22";
            }

            if($result)
            {
                mysqli_commit($_SESSION['mysqli_link']);
                echo(makeresultjson("0","ok"));
            }
            else
            {
                echo(makeresultjson("-1","sql_error@createrole_auth:".$result));
            }

        }
        else
        {
            echo(makeresultjson("-1","sql_error@createMerchantFloor"));
        }
    }
    else
    {
        echo(makeresultjson("-1","sql_error@createMerchant"));
    }



    mysqli_autocommit($_SESSION['mysqli_link'],1);
    return;
}

function getMerchantInfoByMerchantUUID()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }

    $arr_res_oneline = array();
    if($_REQUEST['merchant_uuid']!="all")
    {
        if($_COOKIE['userrole']=="1")
        {
            $sql="select 1 as I,1 as D,1 as M,1 as S,merchant.*,server.name as servername from  merchant  inner join server on server.id=merchant.server_id where  merchant.uuid='".$_REQUEST['merchant_uuid']."'";
        }
        else
        {
            $sql="select I,D,M,S,merchant.*,server.name as servername from role_authority inner join merchant on merchant.id=role_authority.merchant_id inner join server on server.id=merchant.server_id where role_id='".$_COOKIE['userrole']."' and merchant.uuid='".$_REQUEST['merchant_uuid']."'";
        }

        $result = mysqli_query($_SESSION['mysqli_link'], $sql);
        $row = mysqli_fetch_assoc($result);
        //{
        //print_r($row);

        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['uuid']=$row['uuid'];
        $arr_res_oneline['name']=$row['name'];
        $arr_res_oneline['servername']=$row['servername'];
        $arr_res_oneline['address']=$row['address'];
        $arr_res_oneline['I']=$row['I'];
        $arr_res_oneline['D']=$row['D'];
        $arr_res_oneline['M']=$row['M']; ;
        $arr_res_oneline['S']=$row['S'];
        $arr_res_oneline['status']=$row['status'];

        $arr_res_oneline['return_code']="0";
        //}

    }
    else
    {
        $arr_res_oneline['return_code']="1";

    }
    writeLog(json_encode($arr_res_oneline,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res_oneline,JSON_UNESCAPED_UNICODE);
    return;

}


function getStoreTableByMerchantUUID()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    //$sql="select * from store where merchant_uuid='".$_REQUEST['merchant_uuid']."'";
    if($_REQUEST['merchant_uuid']=="all")
    {
        $cond_merchant_uuid="";
    }
    else
    {
        $cond_merchant_uuid="merchant.uuid='".$_REQUEST['merchant_uuid']."' and ";
    }

    if($_COOKIE['userrole']==1)
    {
        $sql="select store.*,merchant.name as merchantname,floor.name as floorname,industry.name as industryname,industry.pid as industrypid from store inner join merchant on merchant.uuid=store.merchant_uuid  left join floor on floor.id=store.floor left join industry on industry.id=store.industry where ".$cond_merchant_uuid." 1=1";
    }
    else
    {
        $sql="select store.*,merchant.name as merchantname,floor.name as floorname,industry.name as industryname,industry.pid as industrypid from store inner join merchant on merchant.uuid=store.merchant_uuid inner join role_authority ra on ra.merchant_id=merchant.id left join floor on floor.id=store.floor left join industry on industry.id=store.industry where ".$cond_merchant_uuid."  ra.role_id='".$_COOKIE['userrole']."'";
    }

    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['uuid']=$row['uuid'];
        $arr_res_oneline['merchant_uuid']=$row['merchant_uuid'];
        $arr_res_oneline['name']=$row['name'];
        $arr_res_oneline['merchantname']=$row['merchantname'];
        $arr_res_oneline['floorname']=$row['floorname'];
        $arr_res_oneline['floor']=$row['floor'];
        $arr_res_oneline['area']=$row['area'];
        $arr_res_oneline['industry']=$row['industry'];
        $arr_res_oneline['industryname']=$row['industryname'];
        $arr_res_oneline['industrypid']=$row['industrypid'];
        $arr_res_oneline['status']=$row['status'];

        array_push($arr_res,$arr_res_oneline);
    }
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function logout()
{
    setcookie("userid", "", time() - 3600);
    setcookie("userrole", "", time() - 3600);
    header('Location: index.html');
    exit();
}

function getMerchantSelectByUserid()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    $sql="select I,D,M,S,merchant.*,server.name as servername from role_authority inner join merchant on merchant.id=role_authority.merchant_id inner join server on server.id=merchant.server_id where role_id='".$_COOKIE['userrole']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['uuid'];
        $arr_res_oneline['text']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getIndustryOption()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    $sql="select * from industry where level=1";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getIndustryOptionDetail()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    $sql="select * from industry where pid='".$_REQUEST['pid']."'";
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['name']=$row['name'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getMerchantTableByUserid()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    if($_COOKIE['userrole']=="1")
    {
        $sql="select 1 as I,1 as D,1 as M,1 as S,merchant.*,server.name as servername,merchanttype.name as merchanttypename from merchant inner join server on server.id=merchant.server_id inner join merchanttype on merchanttype.id=merchant.merchant_type";

    }
    else
    {
        $sql="select I,D,M,S,merchant.*,server.name as servername,merchanttype.name as merchanttypename
from role_authority inner join merchant on merchant.id=role_authority.merchant_id inner join server on server.id=merchant.server_id inner join merchanttype on merchanttype.id=merchant.merchant_type where role_id='".$_COOKIE['userrole']."'";

    }
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['uuid']=$row['uuid'];
        $arr_res_oneline['name']=$row['name'];
        $arr_res_oneline['servername']=$row['servername'];
        $arr_res_oneline['server_id']=$row['server_id'];
        $arr_res_oneline['location_info']=$row['ht_location_info'];
        $arr_res_oneline['address']=$row['address'];
        $arr_res_oneline['area']=$row['area'];
        $arr_res_oneline['address']=$row['address'];
        $arr_res_oneline['merchanttypename']=$row['merchanttypename'];
        $arr_res_oneline['merchant_type']=$row['merchant_type'];
        $arr_res_oneline['I']=$row['I'];
        $arr_res_oneline['D']=$row['D'];
        $arr_res_oneline['M']=$row['M'];
        $arr_res_oneline['S']=$row['S'];
        $arr_res_oneline['status']=$row['status'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function getBriefingTable()
{
    if(!isset($_COOKIE['userid']) ||!$_COOKIE['userrole'])
    {
        die(makeresultjson("-99","need login"));

    }
    $arr_res=array();
    if($_COOKIE['userrole']=="1")
    {
        $sql="select * from briefing order by id desc;";

    }
    else
    {
        $sql="select * from briefing where username='".$_COOKIE['username']."' order by id desc";
    }
    $result = mysqli_query($_SESSION['mysqli_link'], $sql);
    while($row = mysqli_fetch_assoc($result))
    {
        //print_r($row);
        $arr_res_oneline = array();
        $arr_res_oneline['id']=$row['id'];
        $arr_res_oneline['username']=$row['username'];
        $arr_res_oneline['customername']=$row['customername'];
        $arr_res_oneline['customerage']=$row['customerage'];
        $arr_res_oneline['filepath']=$row['filepath'];
        $arr_res_oneline['createtime']=$row['createtime'];
        array_push($arr_res,$arr_res_oneline);
    }
    //$arr_res['return_code']="0";
    writeLog(json_encode($arr_res,JSON_UNESCAPED_UNICODE));
    echo json_encode($arr_res,JSON_UNESCAPED_UNICODE);
    return;
}

function dologin()
{
    //echo $_REQUEST['pwd'];
    if(!isset($_REQUEST['pwd']) ||!isset($_REQUEST['username']))
    {
        die("need pwd & username");
    }
    $referer = $_SERVER['HTTP_REFERER'];

    $sql="select * from user where username='".$_REQUEST['username']."'";

    if ($result = mysqli_query($_SESSION['mysqli_link'], $sql))
    {

        /* Fetch the results of the query 返回查询的结果 */
        $row = mysqli_fetch_assoc($result);
        if(!empty($row)){
            //echo  $row['id'], "&nbsp;", $row['username'], "&nbsp;",  $row['pwd'], "<br/>";
            // printf("%s (%s) ",  $row['id'],$row['class'], $row['scores']);
            $md5pwd=md5($_REQUEST['pwd']);
            if($md5pwd==$row['pwd']) //pwd ok
            {
                setcookie("username", $row['username']);
                setcookie("userid", $row['id']);
                setcookie("userrole", $row['role_id']);
				setcookie("companyname", $row['companyname']);
				setcookie("logopath", $row['logopath']);
				setcookie("tel", $row['tel']);
				setcookie("email", $row['email']);
				setcookie("email2", $row['email2']);
				setcookie("emailname", $row['emailname']);
				setcookie("email2name", $row['email2name']);
				setcookie("price188a", $row['price188a']);
				setcookie("price188b", $row['price188b']);
				setcookie("price188c", $row['price188c']);
				setcookie("price132", $row['price132']);
				
				if($row['role_id']==1)
				{
					header('Location: main.php');
				}
				else
				{
					header('Location: briefing.php');
				}
            }
            else //pwd fail
            {

                echo "<script>alert('密码错误！');location.href='".$referer."'</script>";
            }
        }
        else
        {
            echo "<script>alert('没有此用户信息！');location.href='".$referer."'</script>";
            //header('Location: index.html');
            //exit;
        }

        /* Destroy the result set and free the memory used for it 结束查询释放内存 */

    }
    else // no user in db
    {
        echo "<script>alert('数据库错误！');location.href='".$referer."'</script>";
    }

}

?>